/**************************************************************************************************

	NSurvey - The web survey and form engine
	Copyright (c) 2004, Thomas Zumbrunn. (http://www.nsurvey.org)

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

************************************************************************************************/


namespace Votations.NSurvey.WebAdmin.UserControls
{
	using System;
	using System.Web;
	using System.Web.UI;
	using System.Web.UI.WebControls;
	using System.Resources;
	using Microsoft.VisualBasic;
	using Votations.NSurvey;
	using Votations.NSurvey.Data;
	using Votations.NSurvey.DataAccess;
	using Votations.NSurvey.BusinessRules;
	using Votations.NSurvey.Web;


	/// <summary>
	/// Answer data CU methods
	/// </summary>
	public partial class AnswerOptionControl : UserControl
	{
		public event EventHandler OptionChanged;
		protected System.Web.UI.WebControls.DropDownList DropDownList1;


		/// <summary>
		/// Id of the answer to edit
		/// if no id is given put the 
		/// usercontrol in creation mode
		/// </summary>
		public int AnswerId
		{
			get { return (ViewState["AnswerID"]==null) ? -1 : int.Parse(ViewState["AnswerID"].ToString()); }
			set { ViewState["AnswerID"] = value; }
		}

		/// <summary>
		/// Id of the answer's question 
		/// </summary>
		public int QuestionId
		{
			get { return (ViewState["QuestionId"]==null) ? -1 : int.Parse(ViewState["QuestionId"].ToString()); }
			set { ViewState["QuestionId"] = value; }
		}

		public bool ScoreEnabled
		{
			get { return (ViewState["ScoreEnabled"]==null) ? false : bool.Parse(ViewState["ScoreEnabled"].ToString()); }
			set { ViewState["ScoreEnabled"] = value; }
		}

		public bool RatingEnabled
		{
			get { return (ViewState["RatingEnabled"]==null) ? false : bool.Parse(ViewState["RatingEnabled"].ToString()); }
			set { ViewState["RatingEnabled"] = value; }
		}


		protected void Page_Load(object sender, System.EventArgs e)
		{
			LocalizePage();

			MessageLabel.Visible = false;
			DeleteAnswerButton.Attributes.Add("onClick",
							"javascript:if(confirm('" +((PageBase)Page).GetPageResource("DeleteAnswerConfirmationMessage")+ "')== false) return false;");
		
			if (!Page.IsPostBack)
			{
				BindData();
			}

			AnswerTypeData typeData = new AnswerTypes().GetAnswerTypeById(int.Parse(AnswerTypeDropDownList.SelectedValue));
			SetUIState(typeData.AnswerTypes[0].TypeMode, false);
		}

		private void LocalizePage()
		{
			PipeHelpLabel.Text = ((PageBase)Page).GetPageResource("PipeHelpLabel");
			AnswerRatingLabel.Text = ((PageBase)Page).GetPageResource("AnswerRatingLabel");
			SelectedAnswersLabel.Text = ((PageBase)Page).GetPageResource("SelectedAnswersLabel");
			AnswerURLLabel.Text = ((PageBase)Page).GetPageResource("AnswerURLLabel");
			ScoreLabel.Text = ((PageBase)Page).GetPageResource("ScoreLabel");
			UpdateAnswerButton.Text = ((PageBase)Page).GetPageResource("UpdateAnswerButton");
			DeleteAnswerButton.Text = ((PageBase)Page).GetPageResource("DeleteAnswerButton");
			AddAnswerButton.Text = ((PageBase)Page).GetPageResource("AddAnswerButton");
			AnswerTextLabel.Text = ((PageBase)Page).GetPageResource("AnswerTextLabel");
			AnswerTypeLabel.Text = ((PageBase)Page).GetPageResource("AnswerTypeLabel");
			CancelAnswerButton.Text = ((PageBase)Page).GetPageResource("CancelAnswerButton");
			AnswerPipeAliasLabel.Text = ((PageBase)Page).GetPageResource("AnswerPipeAliasLabel");
		}

		public void BindData()
		{
			if (((PageBase)Page).NSurveyUser.Identity.IsAdmin)
			{
				AnswerTypeDropDownList.DataSource = new AnswerTypes().GetAnswerTypesList();
			}
			else
			{
				AnswerTypeDropDownList.DataSource = new AnswerTypes().GetAssignedAnswerTypesList(((PageBase)Page).NSurveyUser.Identity.UserId);
			}
			
			AnswerTypeDropDownList.DataMember = "AnswerTypes";
			AnswerTypeDropDownList.DataTextField = "Description";
			AnswerTypeDropDownList.DataValueField = "AnswerTypeID";
			AnswerTypeDropDownList.DataBind();
			((PageBase)Page).TranslateListControl(AnswerTypeDropDownList);

			AnswerTypeDropDownList.SelectedValue = "1";

			// Check if any answer has been assigned
			if (AnswerId == -1)
			{
				SwitchToCreationMode();
			}
			else
			{
				SwitchToEditionMode();
			}
		}


		/// <summary>
		/// Setup the control in creation mode
		/// </summary>
		private void SwitchToCreationMode()
		{
			// Creation mode
			AddAnswerButton.Visible = true;
			UpdateAnswerButton.Visible = false;
			DeleteAnswerButton.Visible = false;
			SelectedAnswersLabel.Visible = true;
			SelectionCheckBox.Visible = true;
			RatingPartCheckbox.Visible = RatingEnabled;
			AnswerRatingLabel.Visible = RatingEnabled;
			AnswerTextTextBox.Text = String.Empty;
			AnswerPipeAliasTextBox.Text = String.Empty;
			DefaultTextTextBox.Text = String.Empty;
			ScoreTextBox.Text = String.Empty;
			ScoreTextBox.Visible = ScoreEnabled;
			ScoreLabel.Visible = ScoreEnabled;
			EditAnswerTitle.Text = ((PageBase)Page).GetPageResource("AddNewAnswerTitle");

			DefaultTextLabel.Visible = false;
			DefaultTextTextBox.Visible = false;
			AnswerPipeAliasLabel.Visible = false;
			AnswerPipeAliasTextBox.Visible = false;
		}

		/// <summary>
		/// Setup the control in edition mode
		/// </summary>
		private void SwitchToEditionMode()
		{
			AddAnswerButton.Visible = false;
			UpdateAnswerButton.Visible = true;
			DeleteAnswerButton.Visible = true;
			EditAnswerTitle.Text = ((PageBase)Page).GetPageResource("EditAnswerTitle");
			BindFields();
		}

		/// <summary>
		/// Get the current DB data and fill 
		/// the fields with them
		/// </summary>
		private void BindFields()
		{
			AnswerData answer = new Answers().GetAnswerById(AnswerId);
			AnswerTextTextBox.Text = answer.Answers[0].AnswerText;
			AnswerImageURLTextBox.Text = answer.Answers[0].ImageURL;
			DefaultTextTextBox.Text = answer.Answers[0].DefaultText;
			AnswerPipeAliasTextBox.Text = answer.Answers[0].AnswerPipeAlias;
			SelectionCheckBox.Checked = answer.Answers[0].Selected;
			if (AnswerTypeDropDownList.Items.FindByValue(answer.Answers[0].AnswerTypeId.ToString()) != null)
			{
				AnswerTypeDropDownList.SelectedValue = answer.Answers[0].AnswerTypeId.ToString();
			}
			RatingPartCheckbox.Checked = answer.Answers[0].RatePart;
			RatingPartCheckbox.Visible = RatingEnabled;
			AnswerRatingLabel.Visible = RatingEnabled;
			ScoreTextBox.Text = answer.Answers[0].ScorePoint.ToString();
			ScoreTextBox.Visible = ScoreEnabled;
			ScoreLabel.Visible = ScoreEnabled;
			SetUIState(answer.Answers[0].TypeMode, false);
		}

		/// <summary>
		/// Enable / disable fields depending on the type mode choosen
		/// </summary>
		/// <param name="typeMode"></param>
		private void SetUIState(int typeMode, bool resetValues)
		{
			bool isSelectionType = (((AnswerTypeMode)typeMode & AnswerTypeMode.Selection) > 0);
			bool isFieldType = (((AnswerTypeMode)typeMode & AnswerTypeMode.Field) > 0) ||
				(((AnswerTypeMode)typeMode & AnswerTypeMode.Custom) > 0) ||
				(((AnswerTypeMode)typeMode & AnswerTypeMode.DataSource) > 0);

			SelectedAnswersLabel.Visible = isSelectionType;
			SelectionCheckBox.Visible = isSelectionType;
			RatingPartCheckbox.Visible = isSelectionType && RatingEnabled;
			AnswerRatingLabel.Visible = isSelectionType && RatingEnabled;
			ScoreTextBox.Visible = isSelectionType && ScoreEnabled;
			ScoreLabel.Visible = isSelectionType && ScoreEnabled;			
			PipeHelpLabel.Visible = isFieldType;

			if (resetValues && isFieldType)
			{
				ScoreTextBox.Text = "0";
				RatingPartCheckbox.Checked = false;
				SelectionCheckBox.Checked = false;
			}		

			DefaultTextLabel.Visible = isFieldType;
			DefaultTextTextBox.Visible = isFieldType;
			AnswerPipeAliasLabel.Visible = isFieldType;
			AnswerPipeAliasTextBox.Visible = isFieldType;
		}



		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{

		}
		#endregion

		protected void OnOptionChanged()
		{
			if (OptionChanged != null)
			{
				OptionChanged(this, EventArgs.Empty);
			}
		}

		protected void AddAnswerButton_Click(object sender, System.EventArgs e)
		{
			//Creates a BE and adds it in the DB
			AnswerData answer = new AnswerData();
			AnswerData.AnswersRow newAnswer = answer.Answers.NewAnswersRow();

			newAnswer.QuestionId = QuestionId;
			newAnswer.AnswerText = AnswerTextTextBox.Text;
			newAnswer.ImageURL = AnswerImageURLTextBox.Text;
			newAnswer.AnswerTypeId = 
				int.Parse(AnswerTypeDropDownList.SelectedValue);
			newAnswer.RatePart = RatingPartCheckbox.Checked;
			newAnswer.DefaultText = DefaultTextTextBox.Text;
			newAnswer.Selected = SelectionCheckBox.Checked;
			newAnswer.AnswerPipeAlias = AnswerPipeAliasTextBox.Text;
			answer.Answers.AddAnswersRow(newAnswer);
			new Answer().AddAnswer(answer);
			
			OnOptionChanged();

			AnswerId = -1;
			Visible = false;
		}


		protected void DeleteAnswerButton_Click(object sender, System.EventArgs e)
		{
			new Answer().DeleteAnswer(AnswerId);

			AnswerId = -1;
			Visible = false;
		
			// Let the subscribers know that something changed
			OnOptionChanged();
		}

		protected void UpdateAnswerButton_Click(object sender, System.EventArgs e)
		{
			// Create the updated BE
			AnswerData answer = new AnswerData();
			AnswerData.AnswersRow updatedAnswer = answer.Answers.NewAnswersRow();

			updatedAnswer.AnswerText = AnswerTextTextBox.Text;
			updatedAnswer.ImageURL = AnswerImageURLTextBox.Text;
			updatedAnswer.AnswerTypeId = 
				int.Parse(AnswerTypeDropDownList.SelectedValue);
			updatedAnswer.RatePart = RatingPartCheckbox.Checked;
			updatedAnswer.AnswerId = AnswerId;
			updatedAnswer.DefaultText = DefaultTextTextBox.Text;
			updatedAnswer.Selected = SelectionCheckBox.Checked;
			updatedAnswer.ScorePoint = Information.IsNumeric(ScoreTextBox.Text) ?
				int.Parse(ScoreTextBox.Text) : 0;
			updatedAnswer.AnswerPipeAlias = AnswerPipeAliasTextBox.Text;
			answer.Answers.AddAnswersRow(updatedAnswer);

			new Answer().UpdateAnswer(answer);

			MessageLabel.Visible = true;
			MessageLabel.Text = ((PageBase)Page).GetPageResource("SelectionUpdatedMessage");

			// Let the subscribers know that something changed
			OnOptionChanged();

		}

		protected void AnswerTypeDropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			AnswerTypeData typeData = new AnswerTypes().GetAnswerTypeById(int.Parse(AnswerTypeDropDownList.SelectedValue));
			SetUIState(typeData.AnswerTypes[0].TypeMode, true);
		}

		protected void CancelAnswerButton_Click(object sender, System.EventArgs e)
		{
			AnswerId = -1;
			Visible = false;		
		}
	}
}
